package com.example.show_auto.viewmodel

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.example.show_auto.data.DataStoreManager
import com.example.show_auto.data.GameData
import com.example.show_auto.data.GameDataManager
import com.example.show_auto.data.Guest
import com.example.show_auto.data.PersonalData
import com.example.show_auto.data.PersonalDataManager
import com.example.show_auto.data.MultiUserDataManager
import com.example.show_auto.data.Recipe
import com.example.show_auto.data.SettingsStorage
import com.example.show_auto.utils.HashUtils
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import kotlinx.coroutines.delay

/**
 * 主界面ViewModel
 */
class MainViewModel(application: Application) : AndroidViewModel(application) {

    private val gameDataManager = GameDataManager(application)
    private val personalDataManager = PersonalDataManager(application)
    private val dataStoreManager = DataStoreManager(application)
    private val settingsStorage = SettingsStorage(application)
    
    // UI状态
    private val _uiState = MutableStateFlow(MainUiState())
    val uiState: StateFlow<MainUiState> = _uiState.asStateFlow()
    
    // 游戏数据
    private val _gameData = MutableStateFlow<GameData?>(null)
    val gameData: StateFlow<GameData?> = _gameData.asStateFlow()
    
    // 个人数据
    private val _personalData = MutableStateFlow<PersonalData?>(null)
    val personalData: StateFlow<PersonalData?> = _personalData.asStateFlow()
    
    // 贵客列表
    private val _guests = MutableStateFlow<List<Guest>>(emptyList())
    val guests: StateFlow<List<Guest>> = _guests.asStateFlow()
    
    // 筛选后的菜谱列表
    private val _filteredRecipes = MutableStateFlow<List<Recipe>>(emptyList())
    val filteredRecipes: StateFlow<List<Recipe>> = _filteredRecipes.asStateFlow()
    
    // 符文查询相关状态
    private val _runeRecipes = MutableStateFlow<List<Recipe>>(emptyList())
    val runeRecipes: StateFlow<List<Recipe>> = _runeRecipes.asStateFlow()
    
    private val _isLoadingRuneRecipes = MutableStateFlow(false)
    val isLoadingRuneRecipes: StateFlow<Boolean> = _isLoadingRuneRecipes.asStateFlow()
    
    init {
        loadGameData()
        // 从持久化存储加载数据
        loadPersistedData()
    }
    
    /**
     * 从持久化存储加载数据
     * 优先从多用户系统加载当前用户数据，如果没有则从旧系统加载
     */
    private fun loadPersistedData() {
        viewModelScope.launch {
            val multiUserDataManager = MultiUserDataManager(getApplication())
            
            // 优先检查多用户系统是否有当前用户
            val currentUser = multiUserDataManager.getCurrentUser()
            val currentUserData = currentUser?.let { multiUserDataManager.getUserData(it) }
            
            
            if (currentUserData != null) {
                // 多用户系统有数据，加载当前用户数据
                loadCurrentUserData(currentUserData, multiUserDataManager)
            } else {
                // 多用户系统没有数据，从旧系统加载（兼容性）
                loadLegacyData()
            }
        }
    }
    
    /**
     * 加载当前用户数据（多用户系统）
     */
    private suspend fun loadCurrentUserData(
        userData: MultiUserDataManager.UserData,
        multiUserDataManager: MultiUserDataManager
    ) {
        try {
            // 加载用户的个人数据
            val result = personalDataManager.importPersonalData(userData.personalDataJson)
            
            if (result.isSuccess) {
                val updatedData = result.getOrNull()!!
                _gameData.value = updatedData
                
                // 解析并更新PersonalData
                val personalData = personalDataManager.parsePersonalData(userData.personalDataJson)
                _personalData.value = personalData
                
                // 更新UI状态
                _uiState.value = _uiState.value.copy(
                    isCodeValid = true,
                    validationCode = userData.validationCode,
                    error = null
                )
                
                // 同步到旧系统（兼容性）
                dataStoreManager.saveCodeValidation(true, userData.validationCode)
                dataStoreManager.savePersonalData(userData.personalDataJson)
                
                // 同步光环厨师选择配置
    
            } else {
                _uiState.value = _uiState.value.copy(
                    error = "加载用户数据失败: ${result.exceptionOrNull()?.message}"
                )
            }
        } catch (e: Exception) {
            _uiState.value = _uiState.value.copy(
                error = "加载用户数据失败: ${e.message}"
            )
        }
    }
    
    /**
     * 从旧系统加载数据（兼容性）
     */
    private suspend fun loadLegacyData() {
        try {
            // 使用first()只获取一次数据，避免无限循环
            val isValid = dataStoreManager.getCodeValidation().first()
            if (isValid) {
                _uiState.value = _uiState.value.copy(isCodeValid = true)

                // 加载个人数据
                val personalDataJson = dataStoreManager.getPersonalData().first()
                if (personalDataJson.isNotEmpty()) {
                    try {
                        // 解析PersonalData对象
                        val personalData = personalDataManager.parsePersonalData(personalDataJson)
                        _personalData.value = personalData

                        // 导入个人数据到游戏数据
                        val result = personalDataManager.importPersonalData(personalDataJson)
                        if (result.isSuccess) {
                            val updatedData = result.getOrNull()!!
                            _gameData.value = updatedData
                            _uiState.value = _uiState.value.copy(
                                error = null
                            )
                        } else {
                            _uiState.value = _uiState.value.copy(
                                error = "加载保存的数据失败: ${result.exceptionOrNull()?.message}"
                            )
                        }
                    } catch (e: Exception) {
                        _uiState.value = _uiState.value.copy(
                            error = "加载保存的数据失败: ${e.message}"
                        )
                    }
                } else {
                    // 没有个人数据时清空
                    _personalData.value = null
                }
            }
        } catch (e: Exception) {
            _uiState.value = _uiState.value.copy(
                error = "加载旧系统数据失败: ${e.message}"
            )
        }
    }

    /**
     * 加载游戏数据
     */
    private fun loadGameData() {
        viewModelScope.launch {
            _uiState.value = _uiState.value.copy(isLoading = true, error = null)
            
            gameDataManager.loadGameData()
                .onSuccess { data ->
                    // 检查多用户系统是否有当前用户数据
                    val multiUserDataManager = MultiUserDataManager(getApplication())
                    val currentUser = multiUserDataManager.getCurrentUser()
                    val currentUserData = currentUser?.let { multiUserDataManager.getUserData(it) }
                    
                    val finalData = if (currentUserData != null) {
                        // 多用户系统有数据，优先使用多用户系统的数据
                        val result = personalDataManager.importPersonalData(currentUserData.personalDataJson)
                        if (result.isSuccess) {
                            val updatedData = result.getOrNull()!!
                            // 解析并更新PersonalData
                            val personalData = personalDataManager.parsePersonalData(currentUserData.personalDataJson)
                            _personalData.value = personalData
                            updatedData
                        } else {
                            data
                        }
                    } else if (personalDataManager.hasLocalPersonalData()) {
                        // 多用户系统没有数据，但有旧系统数据，使用旧系统数据
                        val personalDataJson = personalDataManager.getPersonalDataJson()
                        if (personalDataJson.isNotEmpty()) {
                            // 解析PersonalData对象
                            val personalData = personalDataManager.parsePersonalData(personalDataJson)
                            _personalData.value = personalData
                        }
                        
                        val result = personalDataManager.useLocalPersonalData(data)
                        if (result.isSuccess) {
                            val updatedData = result.getOrNull()!!
                            updatedData
                        } else {
                            data
                        }
                    } else {
                        // 没有任何个人数据
                        _personalData.value = null
                        data
                    }

                    _gameData.value = finalData
                    _guests.value = finalData.guests.sortedBy { it.name }
                    _uiState.value = _uiState.value.copy(
                        isLoading = false,
                        isDataLoaded = true
                    )
                }
                .onFailure { error ->
                    _uiState.value = _uiState.value.copy(
                        isLoading = false,
                        error = "数据加载失败: ${error.message}"
                    )
                }
        }
    }

    /**
     * 重新加载游戏数据（清除缓存后重新加载）
     */
    fun reloadGameData() {
        gameDataManager.clearCache()
        loadGameData()
    }

    /**
     * 验证校验码并获取个人数据
     * 对应web项目中的个人数据导入功能
     */
    fun validateCode(code: String) {
        if (code.trim().isEmpty()) {
            _uiState.value = _uiState.value.copy(
                error = "请输入校验码"
            )
            return
        }

        _uiState.value = _uiState.value.copy(isValidating = true, error = null)

        viewModelScope.launch {
            try {
                // 通过API获取个人数据
                val currentData = _gameData.value
                if (currentData == null) {
                    _uiState.value = _uiState.value.copy(
                        isValidating = false,
                        error = "游戏数据未加载完成，请稍后重试"
                    )
                    return@launch
                }

                val result = personalDataManager.importPersonalData(code, currentData)

                if (result.isSuccess) {
                    val updatedData = result.getOrNull()!!
                    _gameData.value = updatedData

                    // 保存到持久化存储
                    val personalDataJson = personalDataManager.getPersonalDataJson()
                    
                    // 解析并更新PersonalData
                    val personalData = personalDataManager.parsePersonalData(personalDataJson)
                    _personalData.value = personalData
                    
                    dataStoreManager.saveCodeValidation(true, code)
                    dataStoreManager.savePersonalData(personalDataJson)

                    _uiState.value = _uiState.value.copy(
                        isValidating = false,
                        isCodeValid = true,
                        validationCode = code
                    )

                } else {
                    _uiState.value = _uiState.value.copy(
                        isValidating = false,
                        isCodeValid = false,
                        error = result.exceptionOrNull()?.message ?: "校验码过期，请重新获取白菜菊花码后再次导入！"
                    )
                }
            } catch (e: Exception) {
                _uiState.value = _uiState.value.copy(
                    isValidating = false,
                    error = "校验码过期，请重新获取白菜菊花码后再次导入！"
                )
            }
        }
    }

    /**
     * 多用户支持的校验码验证
     */
    fun validateCodeForMultiUser(
        code: String,
        isNewUser: Boolean,
        userName: String,
        multiUserDataManager: MultiUserDataManager,
        onSuccess: () -> Unit
    ) {
        if (code.trim().isEmpty()) {
            _uiState.value = _uiState.value.copy(
                error = "请输入校验码"
            )
            return
        }

        _uiState.value = _uiState.value.copy(isValidating = true, error = null)

        viewModelScope.launch {
            try {
                val currentData = _gameData.value
                if (currentData == null) {
                    _uiState.value = _uiState.value.copy(
                        isValidating = false,
                        error = "游戏数据未加载完成，请稍后重试"
                    )
                    return@launch
                }

                val result = personalDataManager.importPersonalData(code, currentData)

                if (result.isSuccess) {
                    val updatedData = result.getOrNull()!!
                    _gameData.value = updatedData

                    // 获取个人数据JSON
                    val personalDataJson = personalDataManager.getPersonalDataJson()
                    
                    // 解析并更新PersonalData
                    val personalData = personalDataManager.parsePersonalData(personalDataJson)
                    _personalData.value = personalData

                    // 保存到多用户管理器
                    val saveSuccess = if (isNewUser) {
                        multiUserDataManager.saveUserData(userName, personalDataJson, code)
                    } else {
                        multiUserDataManager.updateUserData(userName, personalDataJson, code)
                    }

                    if (saveSuccess) {
                        // 同时保存到原有的持久化存储（兼容性）
                        dataStoreManager.saveCodeValidation(true, code)
                        dataStoreManager.savePersonalData(personalDataJson)

                        _uiState.value = _uiState.value.copy(
                            isValidating = false,
                            isCodeValid = true,
                            validationCode = code
                        )

                        // 导入成功后，触发自动读取已修炼
                        triggerAutoLoadUltimateSkills()

                        onSuccess()
                    } else {
                        _uiState.value = _uiState.value.copy(
                            isValidating = false,
                            error = "保存用户数据失败"
                        )
                    }
                } else {
                    _uiState.value = _uiState.value.copy(
                        isValidating = false,
                        isCodeValid = false,
                        error = result.exceptionOrNull()?.message ?: "校验码过期，请重新获取白菜菊花码后再次导入！"
                    )
                }
            } catch (e: Exception) {
                _uiState.value = _uiState.value.copy(
                    isValidating = false,
                    error = "校验码过期，请重新获取白菜菊花码后再次导入！"
                )
            }
        }
    }

    /**
     * 切换到指定用户
     */
    fun switchToUser(
        userData: MultiUserDataManager.UserData,
        multiUserDataManager: MultiUserDataManager,
        onSuccess: () -> Unit
    ) {
        viewModelScope.launch {
            try {
                // 设置当前用户
                multiUserDataManager.setCurrentUser(userData.userName)
                
                // 加载用户的个人数据
                val result = personalDataManager.importPersonalData(userData.personalDataJson)
                
                if (result.isSuccess) {
                    val updatedData = result.getOrNull()!!
                    _gameData.value = updatedData
                    
                    // 解析并更新PersonalData
                    val personalData = personalDataManager.parsePersonalData(userData.personalDataJson)
                    _personalData.value = personalData
                    
                    // 更新UI状态
                    _uiState.value = _uiState.value.copy(
                        isCodeValid = true,
                        validationCode = userData.validationCode,
                        error = null
                    )
                    
                    // 同时更新原有的持久化存储（兼容性）
                    dataStoreManager.saveCodeValidation(true, userData.validationCode)
                    dataStoreManager.savePersonalData(userData.personalDataJson)
                    
                    // 切换用户后，重新同步光环厨师选择配置
                    // 确保数据完全加载后再调用回调
                    delay(200)
                    onSuccess()
                } else {
                    _uiState.value = _uiState.value.copy(
                        error = "切换用户失败: ${result.exceptionOrNull()?.message}"
                    )
                }
            } catch (e: Exception) {
                _uiState.value = _uiState.value.copy(
                    error = "切换用户失败: ${e.message}"
                )
            }
        }
    }

    /**
     * 清空当前用户数据
     */
    fun clearCurrentUserData() {
        viewModelScope.launch {
            // 重新加载原始游戏数据
            loadGameData()
            
            // 清空个人数据
            _personalData.value = null
            
            // 重置UI状态
            _uiState.value = _uiState.value.copy(
                isCodeValid = false,
                validationCode = "",
                error = null
            )
            
            // 清空原有的持久化存储
            dataStoreManager.saveCodeValidation(false, "")
            dataStoreManager.savePersonalData("")
        }
    }

    /**
     * 触发自动读取已修炼（用于切换用户后）
     */
    fun triggerAutoLoadUltimateSkills() {
        // 发送一个特殊的状态，让UI知道需要自动触发读取已修炼
        _uiState.value = _uiState.value.copy(
            shouldAutoLoadUltimate = true
        )
    }

    /**
     * 重置自动读取已修炼状态
     */
    fun resetAutoLoadUltimateFlag() {
        _uiState.value = _uiState.value.copy(
            shouldAutoLoadUltimate = false
        )
    }
    
    /**
     * 选择贵客并筛选菜谱
     */
    fun selectGuest(guest: Guest?) {
        _uiState.value = _uiState.value.copy(selectedGuest = guest)

        if (guest == null) {
            _filteredRecipes.value = emptyList()
            return
        }

        val currentData = _gameData.value ?: return

        val filtered = currentData.recipes.filter { recipe ->
            val isGot = recipe.got
            val hasUncompletedGuest = recipe.hasUncompletedGuest(guest.name)



            isGot && hasUncompletedGuest
        }.sortedWith(
            compareBy<Recipe> { it.rarity }
                .thenBy { it.name }
        )

        _filteredRecipes.value = filtered
    }

    /**
     * 清除选择
     */
    fun clearSelection() {
        selectGuest(null)
    }

    /**
     * 选择符文并筛选菜谱（神级符文碰瓷）
     */
    fun selectRune(runeName: String?) {
        if (runeName.isNullOrBlank()) {
            _filteredRecipes.value = emptyList()
            return
        }

        val currentData = _gameData.value ?: return

        val filtered = currentData.recipes.filter { recipe ->
            // 首先检查是否已拥有菜谱
            val isGot = recipe.got
            // 检查gift字段是否与选择的符文匹配
            val hasMatchingGift = recipe.gift == runeName && recipe.gift != "-"
            // 检查是否未达到神级
            // 个人数据中rank=""(空字符串)会被转换为0，表示未制作
            // rank=0: 未制作，rank=1-3: 已制作但未达神级，rank>=4: 神级及以上
            val notGodLevel = recipe.rank < 4

            isGot && hasMatchingGift && notGodLevel
        }.sortedWith(
            // 按品级从高到低排序（rank越高越靠前）
            compareByDescending<Recipe> { it.rank }
                // 然后按星级从低到高排序
                .thenBy { it.rarity }
                // 最后按名称排序
                .thenBy { it.name }
        )

        _filteredRecipes.value = filtered
    }

    /**
     * 计算指定符文可碰瓷的菜谱数量
     */
    fun getRuneRecipeCount(runeName: String): Int {
        val currentData = _gameData.value ?: return 0
        
        return currentData.recipes.count { recipe ->
            val isGot = recipe.got
            val hasMatchingGift = recipe.gift == runeName && recipe.gift != "-"
            val notGodLevel = recipe.rank < 4
            
            isGot && hasMatchingGift && notGodLevel
        }
    }

    /**
     * 重置状态
     */
    fun reset() {
        _uiState.value = MainUiState()
        _filteredRecipes.value = emptyList()
        loadGameData()
    }
    
    /**
     * 清除错误信息
     */
    fun clearError() {
        _uiState.value = _uiState.value.copy(error = null)
    }

    /**
     * 加载已保存的个人数据
     */
    private fun loadSavedPersonalData() {
        // 检查是否有本地保存的个人数据
        if (personalDataManager.hasLocalPersonalData()) {
            // 如果有本地数据，可以选择自动加载或等待用户选择
            // 这里暂时不自动加载，等待用户选择
            return
        }

        // 如果没有本地数据，不做任何操作，等待用户输入校验码
    }
    
    /**
     * 同步光环厨师选择配置
     * 导入数据成功后，识别游戏数据中所有光环厨师并缓存
     */

    
    /**
     * 获取厨师技能描述（与RecipeCalculatorPage中的逻辑一致）
     */
    private fun getChefSkillDescription(chef: com.example.show_auto.data.Chef, skills: List<com.example.show_auto.data.Skill>): String {
        if (!chef.hasUltimateSkill()) return ""
        val descs = chef.getAllUltimateSkills().mapNotNull { sid ->
            skills.find { it.skillId == sid }?.desc
        }
        return descs.joinToString("\n")
    }

    /**
     * 统一的光环厨师筛选逻辑
     * 基于技能effect字段进行精确判断
     */
    private fun isAuraChef(chef: com.example.show_auto.data.Chef, skills: List<com.example.show_auto.data.Skill>): Boolean {
        if (!chef.hasUltimateSkill()) return false
        
        // 获取厨师的所有修炼技能
        val ultimateSkills = chef.getAllUltimateSkills().mapNotNull { skillId ->
            skills.find { it.skillId == skillId }
        }
        
        // 检查是否有符合条件的光环技能
        return ultimateSkills.any { skill ->
            skill.effect?.any { effect ->
                // 条件1：condition必须是"Partial"或"Next"
                val conditionMatch = effect.condition == "Partial" || effect.condition == "Next"
                
                // 条件2：type必须是技法类型
                val typeMatch = effect.type in listOf("Bake", "Steam", "Boil", "Fry", "Knife", "Stirfry")
                
                // 条件3：value必须大于0
                val valueMatch = (effect.value ?: 0) > 0
                
                conditionMatch && typeMatch && valueMatch
            } ?: false
        }
    }
    
    /**
     * 根据符文查询菜谱
     */
    fun searchRecipesByRune(runeName: String) {
        viewModelScope.launch {
            try {
                _isLoadingRuneRecipes.value = true
                
                // 使用已应用个人数据的游戏数据
                val currentData = _gameData.value ?: run {
                    // 如果没有加载游戏数据，从GameDataManager获取
                    gameDataManager.loadGameData().getOrNull()
                }
                
                if (currentData != null) {
                    // 存储匹配的菜谱名称
                    val matchingRecipeNames = mutableSetOf<String>()
                    
                    // 遍历所有贵客的礼物
                    currentData.guests.forEach { guest ->
                        guest.gifts.forEach { gift ->
                            if (gift.antique == runeName) {
                                matchingRecipeNames.add(gift.recipe)
                            }
                        }
                    }
                    
                    // 根据菜谱名称查找对应的菜谱对象（包含个人拥有状态）
                    val recipes = currentData.recipes.filter { recipe ->
                        matchingRecipeNames.contains(recipe.name)
                    }
                    
                    _runeRecipes.value = recipes
                } else {
                    _runeRecipes.value = emptyList()
                }
            } catch (e: Exception) {
                _runeRecipes.value = emptyList()
            } finally {
                _isLoadingRuneRecipes.value = false
            }
        }
    }
    
    /**
     * 根据多个符文查询菜谱
     */
    fun searchRecipesByMultipleRunes(runeNames: List<String>) {
        viewModelScope.launch {
            try {
                _isLoadingRuneRecipes.value = true
                
                // 使用已应用个人数据的游戏数据
                val currentData = _gameData.value ?: run {
                    // 如果没有加载游戏数据，从GameDataManager获取
                    gameDataManager.loadGameData().getOrNull()
                }
                
                if (currentData != null) {
                    // 按符文分组，存储匹配的菜谱名称
                    val recipesByRune = mutableMapOf<String, MutableSet<String>>()
                    
                    runeNames.forEach { runeName ->
                        recipesByRune[runeName] = mutableSetOf()
                    }
                    
                    // 遍历所有贵客的礼物
                    currentData.guests.forEach { guest ->
                        guest.gifts.forEach { gift ->
                            if (gift.antique in runeNames) {
                                recipesByRune[gift.antique]?.add(gift.recipe)
                            }
                        }
                    }
                    
                    // 收集所有相关菜谱名称
                    val allMatchingRecipeNames = mutableSetOf<String>()
                    recipesByRune.values.forEach { recipes ->
                        allMatchingRecipeNames.addAll(recipes)
                    }
                    
                    // 根据菜谱名称查找对应的菜谱对象（包含个人拥有状态）
                    val recipes = currentData.recipes.filter { recipe ->
                        allMatchingRecipeNames.contains(recipe.name)
                    }
                    
                    _runeRecipes.value = recipes
                } else {
                    _runeRecipes.value = emptyList()
                }
            } catch (e: Exception) {
                _runeRecipes.value = emptyList()
            } finally {
                _isLoadingRuneRecipes.value = false
            }
        }
    }
    
    /**
     * 清除符文查询结果
     */
    fun clearRuneSearch() {
        _runeRecipes.value = emptyList()
    }
}

/**
 * 主界面UI状态
 */
data class MainUiState(
    val isLoading: Boolean = false,
    val isValidating: Boolean = false,
    val isDataLoaded: Boolean = false,
    val isCodeValid: Boolean = false,
    val validationCode: String = "",
    val selectedGuest: Guest? = null,
    val error: String? = null,
    val shouldAutoLoadUltimate: Boolean = false
)
